/**
 * 手机端公共js方法增加文件
 * **/

//如果页面内容过少，则将footer固定到底部
function adjustFooter() {
    var bodyHeight = jQuery('.container').height();

    jQuery('.foot').removeClass('fixed');

    if (bodyHeight < window.innerHeight - 130) {
        jQuery('.foot').addClass('fixed');
    }
}

//滑动到底部时加载新数据
function loadDataScrollingBottom(loadFunc) {
    var timer;
    jQuery(window).scroll(function() {
        if(jQuery(window).scrollTop() + jQuery(window).height() >= jQuery(document).height()) {
            jQuery('.loading-tips').show();

            clearTimeout(timer);

            timer = setTimeout(function() {
                if (loadFunc) loadFunc();
                jQuery('.loading-tips').hide();
            }, 500);
        }
    });
}

//切换tab
var historyCurrentPage = 1;
var historyInit = false;
var unDealOrderCurrentPage = 1;
var unDealOrderInit = false;
function changeTab(current) {

    jQuery('.empty-tips').hide();

    if (current == jQuery('.tab-column.column-4.active')[0]) {
        return;
    }
    jQuery('.tab-column.active').removeClass('active');
    jQuery(current).addClass('active');
    jQuery('#range').val(0);

    var symbol = +jQuery('#symbol').val();
    var contentType = jQuery(current).attr('content-type');
    if (contentType == "out" || contentType == "in") {
        // 改当前可用的钱（币），交易类型，按扭
        var userBalanceShow = jQuery('#userBalanceShow'); // <span>
        var userBalance = jQuery('#userBalance');
        var btn = jQuery('#buyBtc');
        var tradeType = jQuery('#tradeType');
        var canUse = jQuery("#canUse"); // <span>
        var limitBit = {
            "usdBit": 2,
            "cnyBit": 2,
            "btcBit": 4,
            "ltcBit": 4
        };
        var marketPriceLabel = jQuery('#marketPriceLabel');
        jQuery("#amount").val("");
        jQuery("#turnover").val("");
        jQuery("#marketPrice").val("");

        var price = jQuery("#marketPrice");

        if (contentType == "out") {

            price.attr('placeholder', price.attr('data-sell-holder'));

            if (symbol == 0) {
                canUse.html(canUseBtc);
                userBalance.val(jQuery('#userBtcBalance').val());
                userBalanceShow.html(CommaFormatted(floor(userBalance.val(), limitBit.btcBit), 4));
            } else {
                canUse.html(canUseLtc);
                userBalance.val(jQuery('#userLtcBalance').val());
                userBalanceShow.html(CommaFormatted(floor(userBalance.val(), limitBit.ltcBit), 4));
            }
            marketPriceLabel.html(Globle.symbolLabel[symbol]);
            tradeType.val(2);
            btn.html(error_sell);
            btn.addClass('red');
        } else {

            price.attr('placeholder', price.attr('data-holder'));

            if (Globle.siteFlag == 1) {
                canUse.html(canUseCny);
            } else {
                canUse.html(canUseUsd);
            }
            userBalance.val(jQuery('#userCnyBalance').val());
            userBalanceShow.html(CommaFormatted(floor(userBalance.val(), limitBit.cnyBit), 2));
            marketPriceLabel.html(Globle.coinStr);
            tradeType.val(1);
            btn.html(error_buy);
            btn.removeClass('red');
        }
        jQuery('.tab-content').hide();
        jQuery('.tab-content.in').show();
        tradeCalculation(jQuery("#price")[0]);
    } else {
        jQuery('.tab-content').hide();
        jQuery('.tab-content.' + contentType).show();
        if (contentType == "history") {
            jQuery('#historyOrder').html("");
            loadRecord(1, historyCurrentPage, "historyOrder");
        } else {
            jQuery("#incomplete").html("");
            loadRecord(0, unDealOrderCurrentPage, "incomplete");
        }
    }

    adjustFooter();
}

function loadRecord(type, currentPage, appendDom) {
    var url = "/mobileTrade/entrust.do";
    var params = {
        symbol : jQuery("#symbol").val(),
        type : type,
        version:2
    };

    jQuery('.loading-tips').show();
    jQuery.post(url, params, function (data) {
        jQuery('.loading-tips').hide();
        jQuery('.empty-tips').hide();

        if (!trim(data).length) {
            jQuery('#emptyTips' + type).show();
            return;
        }
        jQuery("#" + appendDom).html(data);
        adjustFooter();
    });
}

//显示弹出框
function openDialog(text, config) {
    jQuery('.check-dialog .dialog-tips').text(text);
    jQuery('.check-dialog').show();

    var dialogContentHeight = jQuery('.check-dialog .dialog-content').height();
    jQuery('.check-dialog .dialog-window').css('height', dialogContentHeight + 20);

    if (config && config.autoClose === true) {
        setTimeout(function() {
            jQuery('.check-dialog').hide();
        }, 1000);
    }
}

function openDialog2(text, config) {
    jQuery('.check-dialog .dialog-tips').text(text);
    jQuery('.check-dialog').show();

    var dialogContentHeight = jQuery('.check-dialog .dialog-content').height();
    jQuery('.check-dialog .dialog-window').css('height', dialogContentHeight + 20);
    jQuery('.confirm-btn').bind('click',function () {
        window.location.href="/mobileTrade/toCapital.do";
    })
}

function openPasswordDialog(okCallback, cancelCallback) {
    jQuery('.password-dialog').show();

    jQuery('.password-dialog .ok-btn').unbind('click');
    jQuery('.password-dialog .cancel-btn').unbind('click');
    jQuery('.password-dialog .close-btn').unbind('click');

    function cancelDialog() {
        if(!!cancelCallback){
            cancelCallback();
        }
        jQuery('.password-dialog').hide();
    }

    function cleanDialog() {
        jQuery('#dialogTradePassword').val('');
        jQuery('#dialogTradeErrorTips').hide();
    }

    function resizeDialog() {
        var dialogContentHeight = jQuery('.password-dialog .dialog-content').height();
        jQuery('.password-dialog .dialog-window').css('height', dialogContentHeight + 20);
    }

    jQuery('.password-dialog input').focus(function() {
        jQuery('#dialogTradeErrorTips').hide();
        resizeDialog();
    });

    jQuery('.password-dialog .ok-btn').click(function() {
        var password = jQuery('#dialogTradePassword').val();

        if (trim(password).length < 1) {
            jQuery('#dialogTradeErrorTips').show();
            resizeDialog();
            return;
        }

        (typeof okCallback == 'function') && okCallback(password);
        jQuery('.password-dialog').hide();

        cleanDialog();
    });
    jQuery('.password-dialog .cancel-btn').click(function() {
        cancelDialog();
        cleanDialog();
    });
    jQuery('.password-dialog .close-btn').click(function() {
        cancelDialog();
        cleanDialog();
    });

    resizeDialog();
}

//显示确认弹出框
function openConfirmDialog(text, okCallback, cancelCallback) {
    jQuery('.confirm-dialog .dialog-tips').text(text);
    jQuery('.confirm-dialog').show();

    jQuery('.confirm-dialog .ok-btn').unbind('click');
    jQuery('.confirm-dialog .cancel-btn').unbind('click');
    jQuery('.confirm-dialog .close-btn').unbind('click');

    jQuery('.confirm-dialog .ok-btn').click(function() {
        (typeof okCallback == 'function') && okCallback();
        jQuery('.confirm-dialog').hide();
    });

    function cancelDialog() {
        if(!!cancelCallback){
            cancelCallback();
        }
        jQuery('.confirm-dialog').hide();
    }

    jQuery('.confirm-dialog .cancel-btn').click(function() {
        cancelDialog();
    });
    jQuery('.confirm-dialog .close-btn').click(function() {
        cancelDialog();
    });

    var dialogContentHeight = jQuery('.confirm-dialog .dialog-content').height();
    jQuery('.confirm-dialog .dialog-window').css('height', dialogContentHeight + 20);
}

jQuery(document).ready(function(){
    adjustFooter();

    //后退按钮
    //jQuery('.back-btn').click(function() {
    //    window.history.go(-1);
    //});

    //关闭弹出框
    jQuery('.check-dialog .confirm-btn').click(function() {
       jQuery('.check-dialog').hide();
    });

    jQuery(document.body).click(function(e) {
        if (e.target.tagName && e.target.tagName.toLowerCase() === 'input') {
            jQuery('.foot').removeClass('fixed');
        } else {
            adjustFooter();
        }
    });
});

function CommaFormatted(s, n) {
    var k = n;
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
    t = "";
    for (var i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    var result =t.split("").reverse().join("") + "." + r;
    if(Number(s)<0){
        if(result!=null&&result.substr(0,2)=="-,"){
            result=result.substr(2,result.length);
            result="-"+result;
        }
    }
    if(k==0){
        return result.split(".")[0];
    }
    return result;
}


function submitTradeOrder() {
    var tradeOrderForm = {
        marketPrice : +jQuery("#marketPrice").val(),
        price : +jQuery("#price").val(),
        amount : +jQuery("#amount").val(),
        turnover : accMul(+price, +amount),
        tradeType : +jQuery("#tradeType").val(), // 1：买 2：卖
        symbol : +jQuery("#symbol").val(), // 0 btc, 1 ltc, 2 eth
        isOpen : +jQuery("#isOpen").val(),
        isMarket : +jQuery("#isMarket").val(), // 0 限价 1 市价
        tradePwd : jQuery("#dialogTradePassword").val()
    };
    // 会修改的变量
    var modifyDom = {
        tradePwd: jQuery("#dialogTradePassword"),
        tradePwdPanel : jQuery("#tradePwdPanel"),
        price : jQuery("#price"),
        amount : jQuery("#amount"),
        isOpen : jQuery("#isOpen")
    };
    var userBalance = {
        userCnyBalance : +jQuery("#userCnyBalance").val(),
        userBtcBalance : +jQuery("#userBtcBalance").val(),
        userLtcBalance : +jQuery("#userLtcBalance").val(),
        btcPrice : +jQuery("#btcPrice").val(),
        ltcPrice : +jQuery("#ltcPrice").val()
    };
    submitBtcPreCheck(tradeOrderForm, openDialog, modifyDom, userBalance, openPasswordDialog, "buyBtc");
}

function turnoverValue() {
    jQuery("#turnover").val(getTurnover(+jQuery("#price").val(), +jQuery("#amount").val()))
}

function ltrim(s){
    return s.replace( /^\s*/, "");
}

function rtrim(s){
    return s.replace( /\s*$/, "");
}

function trim(s){
    return rtrim(ltrim(s));
}

function validDateIpt(dateName) {
    jQuery(dateName).val("");
    var box = jQuery(dateName).parent().find(".dateinput_box");
    var year = jQuery(box).find(".year_value").val();
    var month = jQuery(box).find(".month_value").val();
    var dvalue = jQuery(box).find(".day_value").val();
    if(year!=""&&month!="") {
        var days = new Date(year,month,0).getDate();
        for(var i=1;i<=days;++i) {
            if(dvalue==i) {
                month = month.length>1 ? month : "0"+month;
                dvalue = dvalue.length>1 ? dvalue : "0"+dvalue;
                jQuery(dateName).val(year+"-"+month+"-"+dvalue);
                return;
            }
        }
    }
}

function loadAccountRecord(currentPage, id) {
    var url = "/account/record.do";
    var params = {
        from : "mobile",
        currentPage : currentPage
    };

    jQuery('.loading-tips').show();
    jQuery.post(url, params, function (data) {
        jQuery('.loading-tips').hide();
        jQuery('.empty-tips').hide();

        if (!trim(data).length) {
            jQuery('#emptyTips0').show();
            return;
        }

        jQuery('#' + id).append(data);
        adjustFooter();
    });
}
